package com.guoxin.concurrentprogramming.chapter4.producerconsumer;

import java.text.MessageFormat;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class Consumer implements Runnable {
    private BlockingQueue<PCData> queue;

    private static final AtomicInteger COUNT = new AtomicInteger();
    private static final int SLEEP_TIME = 1000;
    private static final Random RANDOM = new Random();

    public Consumer(BlockingQueue<PCData> queue) {
        this.queue = queue;
    }

    public void run() {
        System.out.println("start consumer name: " + Thread.currentThread().getName());
        try {
            while (true) {
                //提取任务
                PCData data = queue.take();
                if (data != null) {
                    //计算平方
                    int re = data.get() * data.get();
                    System.out.println(MessageFormat.format(("{0}*{1}={2}"),data.get(),data.get(),re));
                    Thread.sleep(RANDOM.nextInt(SLEEP_TIME));
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

}
